
<template>
  <div class="asset-inventory">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>资产盘点</span>
          <el-button type="primary" @click="handleCreateTask">创建盘点任务</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="任务编号">
          <el-input v-model="searchForm.taskNo" placeholder="请输入任务编号" clearable />
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="searchForm.taskType" placeholder="请选择任务类型" clearable>
            <el-option label="部门盘点" value="department" />
            <el-option label="检查盘点" value="check" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行部门">
          <el-select v-model="searchForm.department" placeholder="请选择执行部门" clearable>
            <el-option label="财务部" value="finance" />
            <el-option label="行政部" value="admin" />
            <el-option label="技术部" value="tech" />
            <el-option label="市场部" value="marketing" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="searchForm.status" placeholder="请选择任务状态" clearable>
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="taskNo" label="任务编号" width="150" />
        <el-table-column prop="taskType" label="任务类型" width="120">
          <template #default="scope">
            <el-tag :type="getTaskType(scope.row.taskType)">
              {{ getTaskTypeLabel(scope.row.taskType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="执行部门" width="120" />
        <el-table-column prop="executor" label="执行人" width="120" />
        <el-table-column prop="assetCount" label="资产数量" width="100" />
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="status" label="任务状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 'pending'" 
              link type="primary" 
              @click="handleExecute(scope.row)"
            >
              执行盘点
            </el-button>
            <el-button 
              v-if="scope.row.status === 'completed'" 
              link type="primary" 
              @click="handleReport(scope.row)"
            >
              盘点报表
            </el-button>
            <el-button link type="primary" @click="handlePrintQR(scope.row)">打印二维码</el-button>
            <el-button 
              v-if="scope.row.status !== 'completed'" 
              link type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建盘点任务对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      title="创建盘点任务"
      width="600px"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="120px"
      >
        <el-form-item label="任务类型" prop="taskType">
          <el-radio-group v-model="taskForm.taskType" @change="handleTaskTypeChange">
            <el-radio label="department">部门盘点</el-radio>
            <el-radio label="check">检查盘点</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行部门" prop="department">
          <el-select v-model="taskForm.department" placeholder="请选择执行部门" style="width: 100%">
            <el-option label="财务部" value="finance" />
            <el-option label="行政部" value="admin" />
            <el-option label="技术部" value="tech" />
            <el-option label="市场部" value="marketing" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行人" prop="executor">
          <el-select v-model="taskForm.executor" placeholder="请选择执行人" style="width: 100%">
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点范围" prop="range">
          <el-checkbox-group v-model="taskForm.range">
            <el-checkbox label="fixed">固定资产</el-checkbox>
            <el-checkbox label="low_value">低值易耗品</el-checkbox>
            <el-checkbox label="lease">租赁资产</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="任务时效" prop="dateRange">
          <el-date-picker
            v-model="taskForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="taskForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTaskForm">创建任务</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  taskNo: '',
  taskType: '',
  department: '',
  status: ''
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    taskNo: 'PD20230001',
    taskType: 'department',
    department: '技术部',
    executor: '张三',
    assetCount: 25,
    startDate: '2023-12-01',
    endDate: '2023-12-15',
    status: 'pending',
    qrCode: 'PD20230001_QR'
  },
  {
    id: 2,
    taskNo: 'PD20230002',
    taskType: 'check',
    department: '行政部',
    executor: '李四',
    assetCount: 18,
    startDate: '2023-11-15',
    endDate: '2023-11-30',
    status: 'completed',
    qrCode: 'PD20230002_QR'
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 用户选项
const userOptions = ref([
  { id: 1, name: '张三', department: '技术部' },
  { id: 2, name: '李四', department: '行政部' },
  { id: 3, name: '王五', department: '市场部' },
  { id: 4, name: '赵六', department: '财务部' }
])

// 创建任务相关
const taskFormRef = ref()
const taskDialogVisible = ref(false)
const taskForm = reactive({
  taskType: 'department',
  department: '',
  executor: '',
  range: ['fixed', 'low_value'],
  dateRange: [],
  remark: ''
})

const taskRules = reactive({
  taskType: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请选择执行部门', trigger: 'change' }
  ],
  executor: [
    { required: true, message: '请选择执行人', trigger: 'change' }
  ],
  range: [
    { type: 'array', required: true, message: '请选择盘点范围', trigger: 'change' }
  ],
  dateRange: [
    { type: 'array', required: true, message: '请选择任务时效', trigger: 'change' }
  ]
})

// 获取任务类型标签
const getTaskTypeLabel = (taskType) => {
  const typeMap = {
    department: '部门盘点',
    check: '检查盘点'
  }
  return typeMap[taskType] || taskType
}

// 获取任务类型样式
const getTaskType = (taskType) => {
  const typeMap = {
    department: 'primary',
    check: 'success'
  }
  return typeMap[taskType] || ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待执行',
    executing: '执行中',
    completed: '已完成',
    expired: '已过期'
  }
  return statusMap[status] || status
}

// 获取状态样式
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    executing: 'primary',
    completed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || ''
}

// 搜索
const handleSearch = () => {
  console.log('搜索条件：', searchForm)
  ElMessage.success('搜索成功')
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  ElMessage.success('重置成功')
}

// 创建盘点任务
const handleCreateTask = () => {
  // 重置表单
  Object.keys(taskForm).forEach(key => {
    if (key === 'range') {
      taskForm[key] = ['fixed', 'low_value']
    } else if (key === 'taskType') {
      taskForm[key] = 'department'
    } else {
      taskForm[key] = ''
    }
  })
  taskDialogVisible.value = true
}

// 任务类型变化处理
const handleTaskTypeChange = (value) => {
  if (value === 'check') {
    // 检查盘点时，可以选择所有部门
    taskForm.department = ''
  }
}

// 提交任务表单
const submitTaskForm = () => {
  taskFormRef.value.validate((valid) => {
    if (valid) {
      // 实际应该调用API保存数据
      console.log('任务表单数据：', taskForm)
      ElMessage.success('创建任务成功')
      taskDialogVisible.value = false
    }
  })
}

// 查看任务详情
const handleView = (row) => {
  ElMessage.info(`查看任务 ${row.taskNo} 详情`)
}

// 执行盘点
const handleExecute = (row) => {
  router.push(`/asset-inventory/execute/${row.id}`)
}

// 查看盘点报表
const handleReport = (row) => {
  router.push(`/asset-inventory/report/${row.id}`)
}

// 打印二维码
const handlePrintQR = (row) => {
  ElMessage.success(`正在打印任务 ${row.taskNo} 的二维码...`)
  // 实际应该调用打印功能
}

// 删除任务
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除盘点任务 "${row.taskNo}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应该调用API删除
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  // 实际应该重新加载数据
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  // 实际应该重新加载数据
}
</script>

<style scoped>
.asset-inventory {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
